/** Addition Scripts Added to Support Templete Frontend
 * @
 */
// fetching content on index page when scrolling
var __host = 'http://vela_project.dev/';
var __page = 1;

function getCaptcha() {
    var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
    var string_length = 5;
    var captchastring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        captchastring += chars.substring(rnum, rnum + 1);
    }
    $("#captcha").text(captchastring);
}


$(document).ready(function () {

    getCaptcha();
    var container = document.querySelector('#portfolio-wrapper');
    var msnry = new Masonry(container, {
        // options
        columnWidth: 0,
        itemSelector: '.portfolio-item'
    });


  /*  $('#load-more').click(function(){
        __page = parseInt(__page) + 1;
        $.ajax({
            url: __host+'topic/topicloadmore',
            type: 'GET',
            data: {page: __page }
        }).done(function(data){
                $("#portfolio-wrapper").append( data ).masonry( 'appended', data );

            });
    }); */




    /*
     * friend list
     * */
    $('#form_modal').click(function (e) {
        $('#form-modal').modal();
        return false;
    });

    $("a.friendlist").click(function () {
        $.ajax({
            type: 'post',
            url: '/user/friendlist',
            dataType: 'html',

            beforeSend: function () {
                $(".loading").fadeIn(500);
            },
            success: function (data) {
                data = JSON.parse(data);
                $.each(data, function (key, val) {
                    var content = ' <div class="friends_area">' +
                        '<img class="image-avatar" src="' + val.avatar + '" alt="Avatar">' +
                        ' <label style="float:left" class="name">' +
                        '<a href="/user/usersearchprofile/' + val.friend_id + '"><b>' + val.name + '</b></a></label>' +
                        '<a href="/user/inbox/' + val.friend_id + '" style="float:right;padding:8px;color:#000">Inbox</a>' +
                        '</div>';
                    $("#friend-content").append(content);
                });
            },
            complete: function () {

            },
            error: function () {
                //alert('Request time out');
            }
        });

    });


    $(function () {

        $(window).scroll(function () {
            if ($(this).scrollTop() != 0) {
                $('#toTop').fadeIn();
            } else {
                $('#toTop').fadeOut();
            }
        });
        $('#toTop').click(function () {
            $('body,html').animate({scrollTop: 0}, 800);
        });
    });


    /*
     *
     *
     * check image available
     * */

    var image = $(".five.columns");
    $(image).find("img").each(function () {
        if ($(this).attr("src") == '/upload/image/' || $(this).attr("src") == '') {
            $(this).attr("src", '/upload/image/no-img.jpg');
            $(this).css("height", '225');
            $(this).css("width", '225');
        }

    });
    <!-------------------------------------- end image available -------------------------------------------------- -->


    <!--Real time script -->
    $('#newMessageAlert').hide();
    var time = 60000;
    var tid = setTimeout(ajaxRealTimeFetchNewMessage, time);

    function ajaxRealTimeFetchNewMessage() {
        // do some stuff...
        //alert('1');<?php echo $this->url('admin/child',array('controller'=>'user','action'=>'loadnewemailajax')) ?>
        $.ajax({
            url: "/admin/user/loadnewemailajax",
            type: "get"

        }).done(function (data) {

                if (data > 0) {

                    $('#newMessageAlert').empty();
                    $('#newMessageAlert').text(data);
                    $('#newMessageAlert').show('slow');
                    document.title = 'Bạn có ' + data + ' tin mới(s)';
                }

            });
        tid = setTimeout(ajaxRealTimeFetchNewMessage, time); // repeat myself
    }


});
/*-----------------------------------------Tooltips ------------------------------------- */
$(function () {

    var tooltips = $("[title]").tooltip({
        track: true
    });

});
/*-----------------------------------------end Tooltips ------------------------------------- */
/* ------start show price -------- */
$(function () {
    var show_price = $(".show_price");

    $(show_price).each(function () {
        if ($(this).attr("data") == 0) {
            $(this).text("Liên hệ");
            $(this).next().text("");
        }
        if ($(this).attr("price") == 0) {
            $(this).text("Liên hệ");
            $(this).next().text("");
        }

    });
});

function show_price(hide, price) {
    var title = '';
    if (hide == 0) {
        title = "Liên hệ";
    } else {
        title = price + ' VNĐ';
    }
    return title;
}
/*---------- end show price---------- */


function getItemElement(content) {
    var elem = document.createElement('div');
    /*var wRand = Math.random();
     var hRand = Math.random();
     var widthClass = wRand > 0.92 ? 'w4' : wRand > 0.8 ? 'w3' : wRand > 0.6 ? 'w2' : '';
     var heightClass = hRand > 0.85 ? 'h4' : hRand > 0.6 ? 'h3' : hRand > 0.35 ? 'h2' : '';*/
    elem.className = 'one-third column portfolio-item';
    elem.innerHTML = content;

    return elem;
}

$(function () {
    $.resetFormOnFocus();
    $.validateForm(registerComplete);
});

$(function () {
    $(".datepicker").datepicker();
});

//Reset fields
$.resetFormOnFocus = function () {
    $("form.require-validate input").keypress(function () {
        if ($(this).next('span.error-field').length > 0)
            $(this).next('span.error-field').remove();
    });
}
$.resetForm = function (formName) {
    $("form[name=" + formName + "] input:not(input[type=hidden], input[type=submit])").each(function () {
        $(this).val('');
    });
    $("form[name=" + formName + "] textarea").each(function () {
        $(this).val('');
    });
}

//All forms validate
$.validateForm = function (callback_func) {
    $("form.require-validate").submit(function () {

        $('#simplemodal-container').hide();
        $('#simplemodal-overlay').hide();
        var formName = $(this).attr('name');
        $(this).find(".loading").show();
        var pass = true;
        $(this).find(".field").each(function () {
            if ($(this).find('label span').html() == '*') {
                if ($(this).find('input').val() == '') {
                    if (pass) pass = false;
                    if (!($(this).find('input').next('span.error-field').length > 0))
                        $(this).find('input').after('<span class="error-field"><i class="mini-ico-exclamation-sign"></i> <b style="color: #ff0000">Vui lòng điền đầy đủ thông tin vào ô phía trên!</b></span><br/>');
                }
            }
            if ($(this).find('input').hasClass('captcha_require')) {
                var captcha = $('#captcha').text();
                var txt_catpcha = $("#captcha_txt").val();
                if (captcha != txt_catpcha) {
                    getCaptcha();
                    if (pass) pass = false;
                    if (!($(this).find('input').next('span.error-field').length > 0))
                        $(this).find('button').after('<br/><span class="error-field"><i class="mini-ico-exclamation-sign"></i> <b style="color: #ff0000">Mã xác nhận sai!</b></span><br/>');
                }
            }

        });
        $(this).find(".loading").hide();
        if (!pass) return false;
        else {
            if ($(this).hasClass('ajax-form')) {
                if (!($(this).find('input[name=ajax_request]').length > 0))
                    $(this).append('<input type="hidden" name="ajax_request" value = "1">');
                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'html',
                    beforeSend: function () {
                        $(".overlay-loading").fadeIn(500);
                    },
                    success: function (response) {
                        //alert(response);
                        response = JSON.parse(response);
                        $(".overlay-loading").fadeOut(1000);
                        if (response.result) $.resetForm(formName);
                        callback_func(response);

                    },
                    error: function () {
                        jerror('Request timeout');
                        $(".overlay-loading").fadeOut(1000);
                    }
                });
                $(this).find(".loading").hide();
                return false;
            }
            /* ------------------------------- begin register function ------------------------------ */
            if ($(this).hasClass('ajax-form-register')) {
                if (!($(this).find('input[name=ajax_request]').length > 0))
                    $(this).append('<input type="hidden" name="ajax_request" value = "1">');
                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'html',
                    beforeSend: function () {
                        $(".overlay-loading").fadeIn(500);
                    },
                    success: function (response) {
                        //alert(response);
                        response = JSON.parse(response);
                        $(".overlay-loading").fadeOut(1000);
                        if (response.result) $.resetForm(formName);
                        callback_func(response);
                        if (response.register) window.location.href = 'http://' + window.location.host + '/user/profile/' + response.user_id;

                    },
                    error: function () {
                        jerror('Request timeout');
                        $(".overlay-loading").fadeOut(1000);
                    }
                });
                $(this).find(".loading").hide();
                return false;
            }
            /* ------------------------------- begin login function ------------------------------ */
            if ($(this).hasClass('ajax-form-login')) {
                if (!($(this).find('input[name=ajax_request]').length > 0))
                    $(this).append('<input type="hidden" name="ajax_request" value = "1">');
                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'html',
                    beforeSend: function () {
                        $(".overlay-loading").fadeIn(500);
                    },
                    success: function (response) {
                        //alert(response);
                        response = JSON.parse(response);
                        $(".overlay-loading").fadeOut(1000);
                        if (response.result) $.resetForm(formName);
                        callback_func(response);

                        setTimeout(window.location.href = 'http://' + window.location.host, 2000);

                        if (response.confirm == 0) {
                            if (!$("#h4").is(":visible")) {
                                $("#page-title").append("<h4 id='h4' style='color: orangered'>Your email is not verify,Click <span id='verify' style='text-decoration: solid #cccccc 1px;cursor: pointer'>here</span>  to resend </h4>");
                            }
                            $("#verify").click(function () {
                                $.ajax({
                                    url: 'http://' + window.location.host + '/user/confirm',
                                    type: 'POST',
                                    data: { name: response.name, time_reg: response.time_reg, email: response.email },
                                    dataType: 'html',
                                    beforeSend: function () {
                                        $(".overlay-loading").fadeIn(500);
                                    },
                                    success: function (data) {
                                        $(".overlay-loading").fadeOut(1000);
                                        $("#h4").text("Thư xác nhận đã được gửi đến email của bạn").fadeOut(5000);

                                    },
                                    error: function () {

                                    }
                                });
                            });
                        }
                    },
                    error: function () {
                    }
                });
                $(this).find(".loading").hide();
                return false;
            }
            if ($(this).hasClass('ajax-form-comment')) {
                if (!($(this).find('input[name=ajax_request]').length > 0))
                    $(this).append('<input type="hidden" name="ajax_request" value = "1">');
                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'html',
                    beforeSend: function () {
                        $(".overlay-loading").fadeIn(500);
                    },
                    success: function (response) {

                        response = JSON.parse(response);
                        $(".overlay-loading").fadeOut(1000);
                        if (response.result) $.resetForm(formName);
                        callback_func(response);
                        $(".commentlist").append(response.content);

                    },
                    error: function () {
                    }
                });
                $(this).find(".loading").hide();
                return false;
            }
        }
        $(this).find(".loading").hide();
    });
}
function login_form() {
}
function comment_form() {
}

function registerComplete(response) {
    if (response.result == 0 || !(response.result)) {
        jerror(response.message);
    }
    else jsuccess(response.message);
}

//Alert, Notify
jsuccess = function (str_message) {
    jSuccess(
        str_message,
        {
            autoHide: true, // added in v2.0
            clickOverlay: false, // added in v2.0
            MinWidth: 250,
            TimeShown: 3000,
            ShowTimeEffect: 200,
            HideTimeEffect: 200,
            LongTrip: 20,
            HorizontalPosition: 'center',
            VerticalPosition: 'top',
            ShowOverlay: true,
            ColorOverlay: '#FFF',
            OpacityOverlay: 0.3,
            onClosed: function () { // added in v2.0

            },
            onCompleted: function () { // added in v2.0

            }
        });
}
jerror = function (str_message) {
    jError(
        str_message,
        {
            autoHide: true, // added in v2.0
            clickOverlay: false, // added in v2.0
            MinWidth: 250,
            TimeShown: 3000,
            ShowTimeEffect: 200,
            HideTimeEffect: 200,
            LongTrip: 20,
            HorizontalPosition: 'center',
            VerticalPosition: 'top',
            ShowOverlay: true,
            ColorOverlay: '#FFF',
            OpacityOverlay: 0.3,
            onClosed: function () { // added in v2.0

            },
            onCompleted: function () { // added in v2.0

            }
        });
}
jnotify = function (str_message) {
    jNotify(
        str_message,
        {
            autoHide: true, // added in v2.0
            clickOverlay: false, // added in v2.0
            MinWidth: 250,
            TimeShown: 3000,
            ShowTimeEffect: 200,
            HideTimeEffect: 200,
            LongTrip: 20,
            HorizontalPosition: 'center',
            VerticalPosition: 'top',
            ShowOverlay: true,
            ColorOverlay: '#FFF',
            OpacityOverlay: 0.3,
            onClosed: function () { // added in v2.0

            },
            onCompleted: function () { // added in v2.0

            }
        });
}

/*
 *@ Function for ajax register
 */
$(function () {
    $(".avatar-dropzone").click(function () {
        $("#user-register-avatar input[type=file]").click();
    });
    $("#user-register-avatar").fileupload({
        dropZone: $('.avatar-dropzone'),
        url: $(this).attr('action'),
        dataType: 'json',
        crossDomain: true,
        type: 'POST',
        autoUpload: true,
        add: function (event, data) {
            var checkOneInstance = $("input[name=once_instance]").val();
            if (checkOneInstance == 1) {
                jError(
                    'Lỗi! đang upload ảnh, vui lòng đợi trong giây lát.',
                    {
                        autoHide: true, // added in v2.0
                        clickOverlay: false, // added in v2.0
                        MinWidth: 250,
                        TimeShown: 3000,
                        ShowTimeEffect: 200,
                        HideTimeEffect: 200,
                        LongTrip: 20,
                        HorizontalPosition: 'center',
                        VerticalPosition: 'top',
                        ShowOverlay: true,
                        ColorOverlay: '#FFF',
                        OpacityOverlay: 0.3,
                        onClosed: function () { // added in v2.0

                        },
                        onCompleted: function () { // added in v2.0

                        }
                    });
                return false;
            }
            $("input[name=once_instance]").val(1);
            $(".overlay-loading").fadeIn(1000);
            var jqXHR = data.submit();
        },
        send: function (e, data) {
        },
        progress: function (e, data) {
        },
        fail: function (e, data) {
            window.onbeforeunload = null;
        },
        success: function (response) {
            $(".overlay-loading").hide();
            $("input[name=once_instance]").val(0);
            if (response.upload == 1) {
                $(".preview-avatar img").attr('src', response.img_url);
                $("input[name=avatar]").val(response.img_url);
                jsuccess(response.message)
            }
            else jerror(response.message);
        },
        done: function (event, data) {
            $(".overlay-loading").hide();
        }
    });
    $('#select_top_menu').change(function () {
        var href = $('#select_top_menu').find(":selected").val();
        window.location.replace(href);
    })
});
